package com.hzy.fivepalace.admin.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.hzy.fivepalace.admin.interceptors.AppInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;


@EnableWebMvc
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {

    /**
     * 资源映射路径
     */
    @Value("${sys-config.profile}")
    private String profile;

    /**
     * 资源映射路径前缀
     */
    @Value("${sys-config.profile-handler}")
    private String  profileHandler;


    //权限认证拦截器
    @Bean
    public AppInterceptor appInterceptor() {
        return new AppInterceptor();
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //权限认证拦截器
        registry.addInterceptor(appInterceptor()).addPathPatterns("/admin/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 资源映射路径前缀 */
        registry.addResourceHandler(profileHandler+"**")
                .addResourceLocations("file:" + profile + "/");

        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // 解决 doc.html 404 报错
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 解决LocalDateTime类型返回给前端莫名其妙变成数组问题
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //SerializerFeature.WriteMapNullValue 增加可解决
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.WriteMapNullValue);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }


}
